/**
 * index.js
 * 
 * @since 1.0 <2016-3-10> SoChishun <14507247@qq.com> Added.
 */

// 免费字体资源:http://www.fontsquirrel.com 2015-12-4 SoChishun Added.
$(document).ready(function () {
// 布局渲染 2015-12-3 SoChishun Added.
// see:http://layout.jquery-dev.com/index.cfm
    if ('undefined' !== typeof ($.fn.layout)) {
        $('body').layout({
            applyDemoStyles: true,
            spacing_open: 2, //边框的间隙
            spacing_closed: 6, //关闭时边框的间隙
            resizerTip: '可调整大小', //鼠标移到边框时，提示语
            sliderTip: "显示/隐藏面板", //在某个Pane隐藏后，当鼠标移到边框上显示的提示语。
            togglerTip_open: "关闭", //pane打开时，当鼠标移动到边框上按钮上，显示的提示语  
            togglerTip_closed: "打开", //pane关闭时，当鼠标移动到边框上按钮上，显示的提示语  
            togglerLength_open: 150, //pane打开时，边框按钮的长度  
            togglerLength_closed: 300, //pane关闭时，边框按钮的长度,
            // 浏览器改变大小的时候，iframe也跟随缩放 2016-3-10
            onresize: function (name, obj) {
                // 主iframe尺寸自动缩放
                if (name == 'center') {
                    $('main iframe').height(obj.height() - 5);
                }
            },
        }).allowOverflow('north'); // 允许下拉菜单越过框架范围而不出现滚动条
    }
// 导航菜单下拉设置
    if ('undefined' !== typeof ($.fn.superfish)) {
        $('ul.sf-menu').superfish({delay: 100});
    }
// 编辑对话框 2016-3-10
    $('.lnk-edit-dialog-g').on('click', function () {
        var $a = $(this);
        ifrmDialog.open_edit_dialog($a.attr('href'), {title: $a.attr('title') ? $a.attr('title') : $a.text()}, 'item-edit{n}');
        return false;
    })
    $('.lnk-view-dialog-g').on('click', function () {
        var $a = $(this);
        ifrmDialog.open_view_dialog($a.attr('href'), {title: $a.attr('title') ? $a.attr('title') : $a.text()}, 'item-view{n}');
        return false;
    })
// 消息滚动播放插件 2015-12-4 SoChishun Added.
// see:http://www.rjboy.cn/?p=708
    if ('undefined' !== typeof ($.fn.Xslider)) {
        AjaxContainer.load_notices(true);
        setInterval(AjaxContainer.load_notices, 10000); // 10秒重载一次公告
    }
    // 读取站内信消息数量
    AjaxContainer.load_pmcount();
    setInterval(AjaxContainer.load_pmcount, 3000); // 3秒重载一次站内信数量
    // 顶部初始化
    head_init();
    // 侧边栏初始化
    aside_init();
    // 加载最后菜单 2016-3-11
    LastMenu.load();
    HistoryMenu.load();
});
// 侧边栏初始化 2016-3-11
function aside_init() {
    // 侧边栏用户区域
    $('.aside-user-zone .switch').click(function () {
        var $p = $(this).find('i').toggleClass('fa-toggle-on').toggleClass('fa-toggle-off').parent().parent();
        $p.find('legend').toggle();
        $p.find('.content').toggle();
    })
    // 侧边栏时钟区域
    $('.aside-clock-zone .switch').click(function () {
        $(this).find('i').toggleClass('fa-toggle-on').toggleClass('fa-toggle-off').parent().parent().next().toggle();
    })
    // 侧边栏菜单区域
    $('.aside-menu .switch').click(function () {
        var multi = true; // 是否独占展开
        if (multi) {
            $(this).find('i').toggleClass('fa-toggle-on').toggleClass('fa-toggle-off').parent().parent().next().toggle();
        } else {
            $('.aside-menu .switch i').removeClass('fa-toggle-on').addClass('fa-toggle-off');
            $('.aside-menu ul').hide();
            $(this).find('i').toggleClass('fa-toggle-on').toggleClass('fa-toggle-off').parent().parent().next().show();
        }
    })
    // 侧边栏菜单自适应高度 
    $('.aside-menu').height($('.ui-layout-west').height() - $('.aside-clock-zone').height() - $('.aside-user-zone').height() - 10);
    // 日历功能 2015-12-4 SoChishun Added.
    $('.aside-calendar').datepicker({showWeek: true, autoSize: true});
    // 时钟功能
    setInterval(clock, 1000);
    // 点击菜单,保存到访问历史中 2016-3-11
    $('.aside-menu').delegate('a.menu-link', 'click', function () {
        var id = $(this).data('id');
        $('.menu-link').parent().removeClass('active');
        $(this).parent().addClass('active');
        load_iframe($(this).attr('href'));
        LastMenu.set(id);
        HistoryMenu.add(id);
        HistoryMenu.load();
        return false;
    })
}
// 顶部初始化
function head_init() {
// 点击菜单,动态加载iframe
    $('#main_nav').delegate('a.menu-link', 'click', function () {
        var id = $(this).data('id');
        //$('.aside-menu').load($('.aside-menu').data('url').replace('varid', id));
        load_iframe($(this).attr('href'));
        LastMenu.set(id);
        HistoryMenu.add(id);
        HistoryMenu.load();
        return false;
    });
    $('.logo a').on('click', function () {
        load_iframe($(this).attr('href'));
        return false;
    });
    // 历史菜单动态效果 2016-3-11
    $('.lnk-history').hover(function () {
        $(this).find('ul').show();
    }, function () {
        $(this).find('ul').hide();
    });
    // 历史菜单点击
    $('#history_menus').delegate('a', 'click', function () {
        var $a = $(this);
        var id = $a.data('id');
        var className = $a.attr('class');
        switch (className) {
            case 'menu-link':
                // $('.aside-menu').load($('.aside-menu').data('url').replace('varid', id));
                load_iframe($(this).attr('href'));
                LastMenu.set(id);
                break;
            case 'close-link':
                HistoryMenu.remove(id);
                HistoryMenu.load();
                break;
            case 'clear-link':
                HistoryMenu.remove(-1);
                HistoryMenu.load();
                break;
        }
        return false;
    });
}

/**
 * 最后访问菜单
 * @since VER:1.0; DATE:2016-3-11; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
var LastMenu = {
    cookie_key: 'MENU_ID',
    // 记录最后一次点击菜单的编号 2016-3-11
    set: function (menu_id) {
        Cookies.set(this.cookie_key, menu_id ? menu_id : 0);
    },
    get: function () {
        var id = Cookies.get(this.cookie_key);
        return id;
    },
    // 加载最后一次点击菜单的编号
    load: function () {
        var id = Cookies.get(this.cookie_key);
        var selector = ($('#main_nav')[0] ? '#main_nav' : '.aside-menu') + ' a[data-id="' + (undefined == id ? 0 : id) + '"]';
        var url = $(selector).attr('href');
        if (id) {
            // $('.aside-menu').load($('.aside-menu').data('url').replace('varid', id));
        }
        if (url) {
            load_iframe(url);
        }
    }
}


/**
 * 历史菜单
 * [1.0 SoChishun 2015-12-11]
 * [1.1 SoChishun 2016-3-11]
 * @since VER1.0 AT:2015-12-07 BY:SoChishun Email:14507247@qq.com DESC:Added.
 */
var HistoryMenu = {
    cookie_key: 'MENU_HISTORY',
    read: function () {
        // 需要Cookies插件支持,请到https://github.com/js-cookie/js-cookie下载该插件
        if ('undefined' == typeof (Cookies)) {
            return;
        }
        var sids = Cookies.get(this.cookie_key);
        return sids ? sids.split(',') : false;
    },
    save: function (aids) {
        Cookies.set(this.cookie_key, aids.join(','));
    },
    add: function (id) {
        if (!id) {
            return false;
        }
        var aids = this.read();
        if (!aids) {
            aids = [id];
        } else {
            if (aids.indexOf(id + '') < 0) {
                if (10 < aids.push(id)) {
                    aids.shift();
                }
            }
        }
        this.save(aids);
        return true;
    },
    /**
     * 删除标签,返回新标签id
     * @param {type} id
     */
    remove: function (id) {
        if (-1 == id) {
            // 清空所有
            Cookies.remove(this.cookie_key);
            return 0;
        }
        if (!id) {
            return 0;
        }
        var aids = this.read();
        if (!aids) {
            return id;
        }
        var i = aids.indexOf(id + '');
        if (i > -1) {
            aids.splice(i, 1);
            var len = aids.length;
            if (i > len - 1) {
                i = len - 1;
            }
            id = aids[i];
        }
        this.save(aids);
        return id;
    },
    // 2016-3-11
    load: function () {
        $('#history_menus').load($('#history_menus').data('url'));
    }
};
/**
 * Ajax容器
 * @type type
 * @since 1.0 2016-3-12 SoChishun Added.
 */
var AjaxContainer = {
    /**
     * 获取未读站内信数量
     * <br />使用了Su-Sign内容比对技术.
     * @returns {undefined}
     * @since 1.0 2016-3-12 SoChishun Added.
     */
    load_pmcount: function () {
        var $dom = $('#pmcount');
        $.get($dom.data('url'), function (data) {
            if (!data || ($dom.data('sign') && $dom.data('sign') == data.sign)) {
                return;
            }
            $dom.text(data.value);
            $dom.data('sign', data.sign);
        })
    },
    /**
     * 加载公告内容
     * <br />使用了Su-Sign内容比对技术.
     * @param {type} first
     * @returns {undefined}
     * @since VER:1.0; DATE:2016-2-3; AUTHOR:SoChishun; DESC:Added.
     */
    load_notices: function (first) {
        var $dom = $('#slider-content-list');
        var url = $dom.data('url');
        var href = $dom.data('href');
        if (!url || !href) {
            return;
        }
        if (first) {
            // $dom.html('');
            $dom.empty();
        }
        $.post(url.replace('varsign', $dom.data('sign')), function (data) {
            if (!data || ($dom.data('sign') && $dom.data('sign') == data.sign)) {
                return;
            }
            var str = '';
            for (var i in data.value) {
                str += '<li><a href="' + href.replace('varkey', data.value[i].id) + '" target="_blank" title="' + data.value[i].title + '">' + data.value[i].title + '</a></li>';
            }
            $dom.empty();
            $dom.data('sign', data.sign);
            $dom.html(str);
            if (first) {
                // 初始化公告滚动插件 2016-2-3 SoChishun Added.
                $(".notices-slider").Xslider({
                    unitdisplayed: 1,
                    numtoMove: 1,
                    loop: "cycle",
                    dir: "V",
                    autoscroll: 2500,
                    speed: 300
                });
            }
        })
    }
}

/**
 * 计算当前日期在本年度的周数
 * @param {Number} weekStart 每周开始于周几：周日：0，周一：1，周二：2 ...，默认为周日
 * @returns {Number}
 * @since 1.0 <2015-12-4> by http://blog.csdn.net/orain/article/details/7063273
 * @example
 (new Date(2015, 11, 4)).getWeekOfYear(); // 当前日期是本年度第几周
 (new Date(2015, 11, 31)).getWeekOfYear(); // 2015 年度有几周(注意：JS 中月的取值范围为 0~11)
 */
Date.prototype.getWeekOfYear = function (weekStart) {
    weekStart = (weekStart || 0) - 0;
    if (isNaN(weekStart) || weekStart > 6)
        weekStart = 0;
    var year = this.getFullYear();
    var firstDay = new Date(year, 0, 1);
    var firstWeekDays = 7 - firstDay.getDay() + weekStart;
    var dayOfYear = (((new Date(year, this.getMonth(), this.getDate())) - firstDay) / (24 * 3600 * 1000)) + 1;
    return Math.ceil((dayOfYear - firstWeekDays) / 7) + 1;
}

/**
 * 计算当前日期在本月份的周数
 * @param {Number} weekStart 每周开始于周几：周日：0，周一：1，周二：2 ...，默认为周日
 * @returns {Number}
 * @since 1.0 <2015-12-4> by http://blog.csdn.net/orain/article/details/7063273
 * @example
 (new Date(2015, 11, 31)).getWeekOfMonth(); // 当前日期是本月第几周(注意：JS 中月的取值范围为 0~11)
 (new Date(2015, 0, 31)).getWeekOfMonth(); // 2015年度1月有几周
 */
Date.prototype.getWeekOfMonth = function (weekStart) {
    weekStart = (weekStart || 0) - 0;
    if (isNaN(weekStart) || weekStart > 6)
        weekStart = 0;
    var dayOfWeek = this.getDay();
    var day = this.getDate();
    return Math.ceil((day - dayOfWeek - 1) / 7) + ((dayOfWeek >= weekStart) ? 1 : 0);
}

// 动态加载iframe 2016-3-10 SoChishun Added.
function load_iframe(ps_url) {
// 销毁iframe，释放iframe所占用的内存(把iframe指向空白页面，这样可以释放大部分内存).
    var iframe = $('main iframe')[0];
    if (iframe) {
        iframe.src = 'about:blank';
        try {
            iframe.contentWindow.document.write('');
            iframe.contentWindow.document.clear();
        } catch (e) {
        }
        iframe.parentNode.removeChild(iframe); // 把iframe从页面移除
    }
// 创建iframe
    var oIfrm = document.createElement("IFRAME");
    oIfrm.src = ps_url;
    oIfrm.scrolling = "no";
    oIfrm.frameBorder = 0;
    oIfrm.width = '100%';
    oIfrm.height = $('.ui-layout-center').height() - 5;
    $("main").append(oIfrm);
    // loading 2016-3-14
    var loading = '<div id="loading" style="position: absolute; left:50%; top:50%; background-color:#FFF; border:solid 1px #CCC; padding:10px; color:#999; z-index: 999">正在加载数据, 请稍后...</div>';
    $('body').append(loading);
    $(oIfrm).load(function () {
        $('body').find('#loading').remove();
    })
}
/**
 * 获取主容器高度
 * @returns Number
 * @since 1.0 2014-8-12 by sutroon
 */
function get_window_height(offset) {
    if (undefined == offset) {
        offset = 0;
    }
    var winHeight = 0;
    if (window.innerHeight) {
        winHeight = window.innerHeight;
    } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
    }
    return winHeight - offset;
}

/**
 * 时钟功能
 * @returns {undefined}
 * @since 1.0 <2015-12-4> SoChishun Added.
 * @since VER:1.1; DATE:2016-1-18; AUTHOR:SoChishun; DESC:修正日期错误
 * @example <div id="clock"><span title="">----------------- ---:---:---</span><i class="fa fa-sun-o" title=""></i></div>
 *      setInterval(clock, 1000);
 */
function clock() {
    var d = new Date(); // 测试 new Date(2015,12,4,22,0,0)
    var week = ['天', '一', '二', '三', '四', '五', '六'];
    var odate = {'y': d.getFullYear(), 'm': d.getMonth() + 1, 'd': d.getDate(), 'h': d.getHours(), 'i': d.getMinutes(), 's': d.getSeconds()};
    var sdate = odate.y + '-' + (odate.m < 10 ? '0' + odate.m : odate.m) + '-' + (odate.d < 10 ? '0' + odate.d : odate.d);
    var stime = sdate + ' ' + (odate.h < 10 ? '0' + odate.h : odate.h) + ':' + (odate.i < 10 ? '0' + odate.i : odate.i) + ':<em>' + (odate.s < 10 ? '0' + odate.s : odate.s) + '<em>';
    var sdateinfo = '今天是' + sdate + ', 星期' + week[d.getDay()] + ', 第' + d.getWeekOfYear() + '周';
    var swords = [[2, 5, '亲，您还在工作吗？熬夜伤身，赶紧休息哦~'], [5, 6, '您这么早就来啦，现在还是凌晨哦！'], [8, 12, '一日之计在于晨，好好加油哦！'], [12, 13, '享受一顿丰盛的午餐然后美美睡个午觉，为下午的工作补充能量~'], [14, 16, '激情工作中，燃烧吧，小宇宙！'], [17, 18, '准备下班啦，赶紧把手头的工作做个收尾哦~'], [20, 22, '亲，加班呀，辛苦啦...'], [22, 23, '夜深了，您还没休息吗，保重身体哦~']];
    var sword = '';
    for (var i in swords) {
        if (odate.h >= swords[i][0] && odate.h < swords[i][1]) {
            sword = swords[i][2];
            break;
        }
    }
    $('.clock').find('i').removeClass('fa-sun-o').removeClass('fa-moon-o').addClass(odate.h >= 18 ? 'fa-moon-o' : 'fa-sun-o').attr('title', sword);
    $('.clock').find('span').html(stime).attr('title', sdateinfo); // 收起展示
}
// 关闭对话框窗口
function close_dialog(name) {
    $('iframe[name="' + name + '"]').attr('src', "about:blank").parent().dialog('close');
}